<?php
namespace app\admin\controller;

use app\common\model\Coupon as CouponModel;
use app\common\model\CouponLog as LogModel;
/**
 * 优惠券控制器
 */
class Coupon extends Admin 
{
	/**
	 * 优惠券列表
	 * @return array
	 */
	public function index(){
		$map = [];
		$list = CouponModel::where($map)->order('id desc')->paginate();

		$this->assign('list', $list);
		return $this->fetch();
	}

	/**
	 * 新增优惠券
	 */
	public function add(){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[
				'name|优惠券名称' => 'require',
				'price|消费金额' => 'require',	
				'num|发放数量' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($res = CouponModel::create($data)){
				$this->success('新增成功');
			}else{
				$this->error('新增失败');
			}
		}else{
			$this->assign('title','新增优惠券');
			$this->assign('info', null);

			return $this->fetch('edit');
		}
	}

	/**
	 * 编辑优惠券
	 * @param  integer $id 
	 * @return mixed
	 */
	public function edit($id = 0){
		if($this->request->isPost()){
			$data = $this->request->post();
			//验证
			$result = $this->validate($data,[
				'name|优惠券名称' => 'require',
				'price|消费金额' => 'require',	
				'num|发放数量' => 'require'
			]);
			// 验证失败 输出错误信息
			if(true !== $result) $this->error($result);

			if($res = CouponModel::update($data)){
				$this->success('编辑成功');
			}else{
				$this->error('编辑失败');
			}
		}else{
			empty($id) && $this->error('参数错误');

			$info = CouponModel::where('id',$id)->find();
			$this->assign('title','编辑优惠券');
			$this->assign('info', $info);

			return $this->fetch();
		}
	}

	/**
	 * 删除优惠券
	 */
	public function del($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
			$map[] = ['id','in',$id];
		}elseif(is_numeric($id)){
			$map[] = ['id','=',$id];
		}

		if($query = CouponModel::where($map)->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}

	/**
	 * 更新状态
	 * @return mixed
	 */
	public function update(){
		$data = $this->request->param();

		if(empty($data)){
			$this->error('参数错误');
		}	
		
		if($query = CouponModel::update($data)){
			$this->success('更新成功');
		}else{
			$this->error('更新失败');
		}
	}

	/**
	 * 优惠券领取记录
	 * @return array
	 */
	public function logs(){
		$map = [];
		$list = LogModel::with('member,coupon')->where($map)->order('id desc')->paginate();

		$this->assign('list', $list);
		return $this->fetch();
	}

	/**
	 * 删除领取记录
	 */
	public function delLog($id = 0){
		empty($id) && $this->error('参数错误');

		if(is_array($id)){
			$map[] = ['id','in',$id];
		}elseif(is_numeric($id)){
			$map[] = ['id','=',$id];
		}

		if($query = LogModel::where($map)->delete()){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}
}